import React, { useRef, useState } from 'react';
import { connect } from 'umi';
import TableDataBlock from '@/components/TableDataBlock';
import RoleSetForm from './components/RoleSetForm';
import RoleSetRes from './components/RoleSetRes';
const RoleList = (props) => {
  const { loading, dispatch, list } = props;
  const childRef = useRef();
  const [visible, setVisible] = useState(false);
  const [roleVisible, setRoleVisible] = useState(false);

  // 搜索参数
  const searchItems = [
    {
      label: '角色名称',
      name: 'roleName',
    },
  ];

  // table 表头
  const getColumns = [
    {
      title: '角色名称',
      dataIndex: 'roleName',
      width: 200,
    },
    {
      title: '是否是主角色',
      align: 'center',
      dataIndex: 'mainType',
      render: (val) => {
        return val === '1' ? '是' : '否';
      },
    },
    {
      title: '菜单状态',
      type: 'switch',
      dataIndex: 'status',
      render: (val, row) => {
        const { id } = row;
        return {
          auth: true,
          checked: val === '1',
          onClick: () =>
            dispatch({
              type: 'setting/fakeAuthRole',
              payload: {
                id,
                status: val === '0' ? '1' : '0',
              },
              callback: () => {
                handleCallback();
              },
            }),
        };
      },
    },
    {
      title: '备注',
      align: 'center',
      dataIndex: 'remark',
    },
    {
      title: '启用状态',
      type: 'switch',
      fixed: 'right',
      width: 100,
      dataIndex: 'status',
      render: (val, row) => {
        const { idString: roleId } = row;
        return {
          auth: 'roleStatus',
          noAuth: val === '1' ? '启用' : '停用',
          checked: val === '1',
          onClick: () => fetchEdit({ roleId, status: 1 ^ Number(val) }),
        };
      },
    },
    {
      type: 'handle',
      width: 200,
      dataIndex: 'id',
      render: (val, record) => [
        {
          auth: true,
          type: 'edit',
          click: () => handleSaveRole(record),
        },
        {
          auth: true,
          title: '资源配置',
          click: () => fetchGetAccessTree(val),
        },
      ],
    },
  ];
  const handleCallback = () => {
    childRef.current.fetchGetData();
  };
  function listToTree(data) {
    // * 先生成parent建立父子关系
    data = data.map((item) => {
      return {
        ...item,
        key: item.id,
        title: item.accessName,
      };
    });
    const obj = {};
    data.forEach((item) => {
      obj[item.id] = item;
    });
    console.log(obj);
    const parentList = [];
    data.forEach((item) => {
      const parent = obj[item.pid];
      if (parent) {
        // * 当前项有父节点
        parent.children = parent.children || [];
        parent.children.push(item);
      } else {
        // * 当前项没有父节点 -> 顶层
        parentList.push(item);
      }
    });
    return parentList;
  }
  function filterList(list, setList = []) {
    let pidList = list.map((item) => {
      return item.pid;
    });
    return setList.filter((item) => {
      let flag = true;
      pidList.forEach((val) => {
        if (val === item.id) {
          flag = false;
        }
      });
      return flag;
    });
  }
  const fetchGetAccessTree = (id) => {
    dispatch({
      type: 'setting/fetchGetAccessTree',
      payload: { roleId: id },
      callback: (e) => {
        const { allAccessList, roleAccessList } = e;
        console.log(filterList(allAccessList, roleAccessList));
        setRoleVisible({
          show: true,
          detail: {
            allAccessList: listToTree(allAccessList),
            roleAccessList: filterList(allAccessList, roleAccessList),
            roleId: id,
          },
        });
      },
    });
  };
  const handleSaveRole = (detail = {}) => {
    setVisible({
      show: true,
      detail,
    });
  };
  const extraBtn = [
    {
      text: '新增',
      onClick: () => {
        handleSaveRole();
      },
    },
  ];
  console.log(visible);
  return (
    <>
      <TableDataBlock
        btnExtra={extraBtn}
        cRef={childRef}
        loading={loading}
        searchItems={searchItems}
        columns={getColumns}
        rowKey={(record) => `${record.id}`}
        dispatchType="setting/fetchListRole"
        {...list}
      ></TableDataBlock>
      <RoleSetForm
        handleCallback={handleCallback}
        childRef={childRef}
        visible={visible}
        onClose={() => setVisible(false)}
      ></RoleSetForm>
      <RoleSetRes visible={roleVisible} onClose={() => setRoleVisible(false)}></RoleSetRes>
    </>
  );
};

export default connect(({ setting, loading }) => ({
  list: setting.list,
  loading: loading.models.setting,
}))(RoleList);
